package com.example.tbplus14.utils.poi;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import lombok.Data;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedWriter;
import java.io.File;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.tbplus14.utils.html.Html2PDFTest.RESOURCE_PATH;

public class FreeMarkerWordUtil {


//    public static final IConverter converter = LocalConverter.builder().build();

    public static void main(String[] args) throws Exception{

        StopWatch stopwatch = new StopWatch();
        stopwatch.start("组装");
        /*
         * 创建一个Map对象，将Word文档需要的数据都保存到该Map对象中
         */
        Map<String, Object> dataMap = new HashMap<>();

        /*
         * 直接在map里保存一个用户的各项信息
         * 该用户信息用于Word文档中FreeMarker普通文本处理
         * 模板文档占位符${name}中的name即指定使用这里的name属性的值"用户1"替换
         */
        dataMap.put("title", "巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表");
        dataMap.put("first", "巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表");
        dataMap.put("second", "巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表");

        // 使用FreeMarker在Word文档中生成图片时，需要将图片的内容转换成Base64编码的字符串

//            dataMap.put("userObj", user2);

        List<TableData> data = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            StringBuilder stringBuffer = new StringBuilder();
            for (int j = 0; j < i + 1; j++) {
                stringBuffer.append(j);
            }
            data.add(new TableData(i + "", i + "", i + "", stringBuffer.toString()));
        }
        data.remove(0);
        dataMap.put("tableList", data);
        // 保存路径
        ClassPathResource imgBaseUrl = new ClassPathResource(RESOURCE_PATH);
        String imgPath = imgBaseUrl.getURL().getPath();

        stopwatch.stop();
        stopwatch.start("创建图");
        dataMap.put("faultRatioImg", Base64.encode(FileUtil.readBytes(imgPath + "bingtu.png")));
        dataMap.put("faultTypeImg", Base64.encode(FileUtil.readBytes(imgPath + "huantu.png")));
        stopwatch.stop();
        stopwatch.start("生成word");

        generateWord(dataMap, "template.ftl", imgPath + "createWord.doc");

//        stopwatch.stop();
//        stopwatch.start("转pdf读取流");
//        File inputFile = new File(imgPath + "createWord.doc");
//        File outputFile = new File(imgPath + "createWord.pdf");
//        try {
//            InputStream docxInputStream = Files.newInputStream(inputFile.toPath());
//            OutputStream outputStream = Files.newOutputStream(outputFile.toPath());
//            stopwatch.stop();
//            stopwatch.start("创建IConverter");
//
//            stopwatch.stop();
//            stopwatch.start("转换");
//            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
//            outputStream.close();
////            converter.shutDown();
//            stopwatch.stop();
//            System.out.println(stopwatch.prettyPrint(TimeUnit.SECONDS));
//            System.out.println("转换完成！");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }



    public static File createPdf(Map<String, Object> dataMap, String templateName, String fileNameNoExtensionName) throws Exception{
//        Map<String, Object> dataMap = new HashMap<>();

        dataMap.put("title", "巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表");
        dataMap.put("first", "巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表");
        dataMap.put("second", "巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表巡检报告2025测试的巡检报告列表明细导出pdf结果集合列表");

        List<TableData> data = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            StringBuilder stringBuffer = new StringBuilder();
            for (int j = 0; j < i + 1; j++) {
                stringBuffer.append(j);
            }
            data.add(new TableData(i + "", i + "", i + "", stringBuffer.toString()));
        }
        data.remove(0);
        dataMap.put("tableList", data);
        // 保存路径
        ClassPathResource baseUrl = new ClassPathResource("/static/");
        String basePath = baseUrl.getURL().getPath();

        dataMap.put("imgBingtu", Base64.encode(FileUtil.readBytes(basePath + "bingtu.png")));
        dataMap.put("imgHuantu", Base64.encode(FileUtil.readBytes(basePath + "huantu.png")));

        // 生成word
        generateWord(dataMap, templateName, String.format("%s%s.docx", basePath, fileNameNoExtensionName));

        return null;
//        // word转pdf
//        File inputFile = new File(String.format("%s%s.docx", basePath, fileNameNoExtensionName));
//        File outputFile = new File(String.format("%s%s.pdf", basePath, fileNameNoExtensionName));
//        try {
//            InputStream docxInputStream = Files.newInputStream(inputFile.toPath());
//            OutputStream outputStream = Files.newOutputStream(outputFile.toPath());
//            IConverter converter = LocalConverter.builder().build();
//            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
//            outputStream.close();
//            converter.shutDown();
//            System.out.println("转换完成！");
//        } catch (Exception e) {
//            throw new RuntimeException("创建pdf文件异常", e);
//        }finally {
//            FileUtil.del(inputFile);
//        }
//        return outputFile;
    }

    @Data
    public static class TableData{
        private String name;
        private String type;
        private String level;
        private String desc;

        public TableData(String name, String type, String level, String desc) {
            this.name = name;
            this.type = type;
            this.level = level;
            this.desc = desc;
        }
    }


    public static void generateWord(Map<String, Object> dataMap, String templateName, String fileName) throws Exception {
        // 设置FreeMarker的版本和编码格式
        Configuration configuration = new Configuration(new Version("2.3.28"));
        configuration.setDefaultEncoding("UTF-8");


        ClassPathResource pdfResource = new ClassPathResource(RESOURCE_PATH);
        String fontPath = pdfResource.getURL().getPath() + File.separator + "static/font/";

        // 设置FreeMarker生成Word文档所需要的模板的路径
        configuration.setDirectoryForTemplateLoading(new File(fontPath));
        // 设置FreeMarker生成Word文档所需要的模板
        Template t = configuration.getTemplate("template.ftl", "UTF-8");
        // 创建一个Word文档的输出流
        Writer out = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(new File(fileName).toPath())
                , StandardCharsets.UTF_8));
        //FreeMarker使用Word模板和数据生成Word文档
        t.process(dataMap, out);
        out.flush();
        out.close();
    }


}
